const path = require('path')
const fs = require('fs')
const isTest = false;

const mergeProject = require('./mergeProject');
const promptConfig = {
    'angular': require('./config/anguarl.js'),
    'react': require('./config/react'),
    'vue': require('./config/vue')
}
const {
    sortDependencies,
    installDependencies,
    runLintFix,
    printMessage,
} = require('./utils/index')
const pkg = require('./package.json')

const templateVersion = pkg.version
const fileMerge = require('./utils/fileMerge')

const {addTestAnswers} = require('./scenarios')

let baseConfig = {
    metalsmith: {
        // When running tests for the template, this adds answers for the selected scenario
        before: addTestAnswers
    },
    helpers: {
        if_or(v1, v2, options) {

            if (v1 || v2) {
                return options.fn(this)
            }

            return options.inverse(this)
        },
        template_version() {
            return templateVersion
        },
    },
    prompts: {
        name: {
            when: 'isNotTest',
            type: 'string',
            required: true,
            message: '项目名称',
        },
        description: {
            when: 'isNotTest',
            type: 'string',
            required: false,
            message: 'Project description',
            default: '鸟瞰智能项目描述',
        },
        author: {
            when: 'isNotTest',
            type: 'string',
            message: '作者',
        }
    },
    filters: {
        '.eslintrc.js': 'lint',
        '.eslintignore': 'lint',
        'test/*': isTest,
        'config/test.env.js': isTest,
        'build/webpack.test.conf.js': isTest,
        'config/test.env.js': 'unit || e2e',
        'build/webpack.test.conf.js': "unit && runner === 'karma'",
        'test/unit/**/*': 'unit',
        'test/unit/index.js': "unit && runner === 'karma'",
        'test/unit/jest.conf.js': "unit && runner === 'jest'",
        'test/unit/karma.conf.js': "unit && runner === 'karma'",
        'test/unit/specs/index.js': "unit && runner === 'karma'",
        'test/unit/setup.js': "unit && runner === 'jest'",
        'test/e2e/**/*': 'e2e',
        'src/router/**/*': 'router',
        'src/store/**/*': 'vuex', // add 加入自己的目录
        'src/http.js': 'http', //add 加入自己的目录
    },
    /**
     * 编译完成回调
     */
    compileComplete(files, metalsmith, done) {
        const metaData = metalsmith.metadata();
        const baseDirName = 'base', tmpName = metaData.template, baseReg = new RegExp(`^${baseDirName}\/`, 'g'),
            tmpReg = new RegExp(`^${tmpName}\/`, 'g'), isPackageJsonReg = /package.json$/g;

        /**
         * 删除冗余模板
         * @param key
         */
        const delFile = function (key) {
            const isBaseFile = baseReg.test(key), isTempFile = tmpReg.test(key);
            if (!isBaseFile && !isTempFile) {
                delete files[key];
                return;
            }
        }
        /**
         * 合并替换文件
         */
        const mergeFile = function (key) {
            const isTempFile = tmpReg.test(key);
            if (isTempFile) {
                const pathKey = path.join(baseDirName, key.replace(tmpReg, ''));
                files[pathKey] = files[key];
                delete files[key];
            }
        }
        /**
         * 修改文件目录结构
         * @param key
         */
        const formatPath = function (key) {
            const pathKey = key.replace(baseReg, '');
            files[pathKey] = files[key];
            delete files[key];
        }

        forEach(files, delFile);
        forEach(files, mergeFile);
        forEach(files, formatPath);
        done();
    },
    complete: function (data, {chalk}) {
        /*console.log(data);
        data.template = 'angular';
        /!*
            先复制，如果有重名的覆盖 package.json除外
            取出base和angular的packagejson数据，然后融合
        *!/
        mergeProject.copy('./template/' + data.template, './template/base', () => {
            console.log('拷贝结束');
        });
        mergeProject.createNewJson('./template/' + data.template + '/package.json', './template/base/package.json');*/
        const green = chalk.green

        sortDependencies(data, green)

        const cwd = path.join(process.cwd(), data.inPlace ? '' : data.destDirName)

        if (data.autoInstall) {
            installDependencies(cwd, data.autoInstall, green)
                .then(() => {
                    return runLintFix(cwd, data, green)
                })
                .then(() => {
                    printMessage(data, green)
                })
                .catch(e => {
                    console.log(chalk.red('Error:'), e)
                })
        } else {
            printMessage(data, chalk)
        }

    }
}

module.exports = function (originData) {
    originData.template = 'angular';
    let newPrompt = Object.assign({}, baseConfig.prompts, promptConfig[originData.template].prompts);
    baseConfig.prompts = newPrompt;
    return baseConfig;
}
